﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Security.Cryptography;

namespace Stp.Core
{
    public static class PasswordGenerator
    {
        private static string _password;
        private static Random _random = new Random();
        private static SHA256Managed _sha256 = new SHA256Managed();
        private static byte[] _pswHash;

        public static string GetRandom(out byte[] pswHash)
        {
            do
            {
                GeneratePassword();
            } while (!PasswordIsValid());

            pswHash = _pswHash;
            return _password;
        }

        private static void GeneratePassword()
        {
            byte[] bits = BitConverter.GetBytes(_random.Next());
            bits = _sha256.ComputeHash(bits);
            _password = Convert.ToBase64String(bits).Substring(0, 8);
            _pswHash = _sha256.ComputeHash(Convert.FromBase64String(_password));
        }

        private static bool PasswordIsValid()
        {
            if (_password.Length == 8)
            {
                return Regex.IsMatch(_password, @"\w{8}");
            }
            else
                return false;
        }
    }
}
